import { Component, Prop } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import type { VxeTableDataRow } from 'vxe-table'
import type { AnyObject } from 'ant-design-vue/es/_util/type'
import type { FilterDto } from '@/render/FilterRender'
import {
    changeRole,
    getSeatInfo,
    getTeamMembersList,
    ressetMiniProgramPassword,
    ressetPcPassword,
    setAdmin,
    setPcAdmin,
    setSeatAdmin,
    toggleLoginPcStatus,
    updatePayManagerUser
} from '@/api/pay'
import { RoleCnEnum } from '@/const/enum'
import {
    CheckOutlined,
    DownOutlined,
    EditOutlined,
    ExclamationCircleFilled,
    EyeInvisibleOutlined,
    EyeOutlined,
    FormOutlined
} from '@ant-design/icons-vue'
import renderModal, {
    getModelValue,
    initModelValue,
    type FormModalDto
} from '@/components/modal/Modal'
import { Button, Dropdown, Menu, MenuItem, message, Switch, Tooltip } from 'ant-design-vue'
import { confirm } from '@/utils/util'
import type { SeatDto } from '@/api/pay/types'

type FormType =
    | 'resetPhoneFormConfig'
    | 'editRoleFormConfig'
    | 'resetMiniProgramPasswordFormConfig'
    | 'resetPcPasswordFormConfig'

@Component
export class TeamManagement extends TableRender {
    @Prop() companyId!: number

    curRowData = {} as VxeTableDataRow

    seatData = {} as SeatDto

    isEyeOpen = false

    filterConfig() {
        return {
            searchText: {
                name: '搜索成员',
                element: 'input'
            }
        } as FilterDto
    }

    tableColumnConfigOld = () => [
        {
            field: 'userName',
            title: '姓名'
        },
        {
            field: 'phone',
            title: '手机号',
            width: 120,
            slots: {
                default: ({ row }) => {
                    return (
                        <div class="flex items-center">
                            <span>{row.phone}</span>
                            <div
                                class="cursor-pointer ml-6px"
                                onClick={() => this.onShowFormModal(row, 'resetPhoneFormConfig')}
                            >
                                <FormOutlined color="#3E5FF5" />
                            </div>
                        </div>
                    )
                }
            }
        },
        {
            field: 'isAdmin',
            title: '角色权限',
            slots: {
                default: ({ row }) => {
                    return row.isAdmin === RoleCnEnum.超级管理员 ? (
                        <div>{RoleCnEnum[row.isAdmin]}</div>
                    ) : (
                        <Tooltip
                            v-slots={{
                                title: () => {
                                    return (
                                        <div class="px-10px py-5px">
                                            <div
                                                class="cursor-pointer mb-5px"
                                                onClick={() => this.onSetRole(row, RoleCnEnum.超级管理员)}
                                            >
                                                <span class="ml-20px">转交为超管</span>
                                            </div>
                                            <div
                                                class="cursor-pointer flex items-center mb-5px"
                                                onClick={() => this.onSetRole(row, RoleCnEnum.管理员)}
                                            >
                                                <div class="w-20px flex items-center">
                                                    {row.isAdmin === RoleCnEnum.管理员 ? (
                                                        <CheckOutlined />
                                                    ) : (
                                                        <div></div>
                                                    )}
                                                </div>
                                                <span>管理员</span>
                                            </div>
                                            <div
                                                class="cursor-pointer flex items-center"
                                                onClick={() => this.onSetRole(row, RoleCnEnum.普通成员)}
                                            >
                                                <div class="w-20px">
                                                    {row.isAdmin === RoleCnEnum.普通成员 ? (
                                                        <CheckOutlined />
                                                    ) : (
                                                        <div></div>
                                                    )}
                                                </div>
                                                <span>普通成员</span>
                                            </div>
                                        </div>
                                    )
                                }
                            }}
                        >
                            <div class="cursor-pointer inline-block">
                                <span class="mr-5px">{RoleCnEnum[row.isAdmin]}</span>
                                <DownOutlined style={{ 'font-size': '12px' }} />
                            </div>
                        </Tooltip>
                    )
                }
            }
        },
        {
            field: 'isSeatAdmin',
            title: '发薪席位',
            slots: {
                default: ({ row }) => {
                    console.log(3333, row.isSeatAdmin)
                    return (
                        <Switch
                            checked={row.isSeatAdmin}
                            onChange={() => this.onToggleSeatAdmin(row)}
                        />
                    )
                }
            }
        },
        // {
        //     field: 'operate',
        //     title: '操作',
        //     fixed: 'right',
        //     width: 200,
        //     params: {
        //         buttons: [
        //             {
        //                 text: '重置密码',
        //                 event: (row) => {}
        //             }
        //         ]
        //     },
        //     slots: {
        //         default: 'buttons'
        //     }
        // },
        {
            field: 'operate',
            title: '操作',
            width: 200,
            fixed: 'right',
            slots: {
                default: ({ row }) => {
                    return (
                        <div class="flex gap-x-10px">
                            <Tooltip
                                v-slots={{
                                    title: () => {
                                        return (
                                            <div class="px-10px py-5px">
                                                <div
                                                    class="cursor-pointer mb-5px"
                                                    onClick={() =>
                                                        this.onShowFormModal(
                                                            row,
                                                            'resetMiniProgramPasswordFormConfig'
                                                        )
                                                    }
                                                >
                                                    重置小程序密码
                                                </div>
                                                <div
                                                    class="cursor-pointer"
                                                    onClick={() =>
                                                        this.onShowFormModal(
                                                            row,
                                                            'resetPcPasswordFormConfig'
                                                        )
                                                    }
                                                >
                                                    重置pc登录密码
                                                </div>
                                            </div>
                                        )
                                    }
                                }}
                            >
                                <Button type="link">修改密码</Button>
                            </Tooltip>
                        </div>
                    )
                }
            }
        }
    ] as TableRenderColumnTypes<VxeTableDataRow>

    // 重置手机号码
    resetPhoneFormConfig = this.initResetPhoneFormConfig() as FormModalDto
    initResetPhoneFormConfig() {
        return {
            title: '重置手机号',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                userName: {
                    name: '已选用户',
                    element: 'input',
                    required: true
                },
                phone: {
                    name: '确认新号码',
                    element: 'input',
                    required: true
                }
            },
            complete: async () => {
                const data = getModelValue(this.resetPhoneFormConfig)
                data.id = this.curRowData.id
                data.userId = this.curRowData.userId
                await updatePayManagerUser(data)
                message.success('更新成功')
                this.reloadPage()
                this.resetPhoneFormConfig.show = false
            },
            cancel: () => {
                this.resetPhoneFormConfig.show = false
            },
            init: () => {
                initModelValue(this.resetPhoneFormConfig, this.curRowData)
            }
        } as FormModalDto
    }

    // 修改角色
    editRoleFormConfig = this.initEditRoleFormConfig() as FormModalDto
    initEditRoleFormConfig() {
        return {
            title: '修改角色',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                userName: {
                    name: '已选用户',
                    element: 'text',
                    params: {
                        class: 'text-blue-default'
                    }
                },
                platform: {
                    name: '平台权限',
                    element: 'select',
                    required: true,
                    options: [
                        {
                            label: '发薪小程序',
                            value: 0
                        },
                        {
                            label: 'PC端',
                            value: 1
                        }
                    ]
                },
                role: {
                    name: '用户角色',
                    element: 'radioGroup',
                    required: true,
                    options: [
                        {
                            label: '管理员',
                            value: 1
                        },
                        {
                            label: '普通成员',
                            value: 0
                        }
                    ],
                    callback: {
                        change: (value: number) => {
                            console.log(1234, value)

                            if (value === 1) {
                                this.editRoleFormConfig.items.hint.value =
                                    '除子弹发薪外的团队管理者角色，可查看操作除子弹发薪外的其他已开通产品权限。管理员拥有对团队人员、团队账户、团队项目的操作管理权限。'
                            } else if (value === 0) {
                                this.editRoleFormConfig.items.hint.value =
                                    '团队普通成员角色，可查看操作除子弹发薪外其他已开通产品的团队项目权限。'
                            }
                            this.editRoleFormConfig.items.hint.hidden = false
                        }
                    }
                },
                hint: {
                    name: '',
                    element: 'text',
                    hidden: true,
                    defaultValue: ''
                }
            },
            complete: async () => {
                const data = getModelValue(this.editRoleFormConfig)
                if (data.platform === 0) {
                    await setAdmin({
                        companyId: this.companyId,
                        userId: this.curRowData.userId,
                        type: 0,
                        isAdmin: data.role
                    })
                } else if (data.platform === 1) {
                    await setPcAdmin({
                        id: this.curRowData.id,
                        isAdmin: data.role
                    })
                }
                message.success('更新成功')
                this.reloadPage()
                this.resetPhoneFormConfig.show = false
            },
            cancel: () => {
                this.resetPhoneFormConfig.show = false
            },
            init: () => {
                initModelValue(this.editRoleFormConfig, this.curRowData)
            }
        } as FormModalDto
    }

    // 重置小程序密码
    resetMiniProgramPasswordFormConfig =
        this.initResetMiniProgramPasswordFormConfig() as FormModalDto
    initResetMiniProgramPasswordFormConfig() {
        return {
            title: '重置小程序密码',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                password: {
                    name: '当前登录密码',
                    element: 'input',
                    placeholder: '请输入当前登录密码',
                    type: 'password',
                    required: true,
                    params: {
                        suffix: () => (
                            <div
                                class="cursor-pointer"
                                onClick={() => this.toggleEye('resetMiniProgramPasswordFormConfig')}
                            >
                                {this.isEyeOpen ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                            </div>
                        )
                    }
                }
            },
            complete: async () => {
                const data = getModelValue(this.resetMiniProgramPasswordFormConfig)
                await confirm('重置密码后客户密码将变为初始密码，请及时提醒客户更改密码。', '提示')
                await ressetMiniProgramPassword({
                    id: this.curRowData.id,
                    password: data.password,
                    userType: '02'
                })
                message.success('更新成功')
                this.reloadPage()
                this.resetMiniProgramPasswordFormConfig.show = false
            },
            cancel: () => {
                this.resetMiniProgramPasswordFormConfig.show = false
            },
            init: () => {
                initModelValue(this.resetMiniProgramPasswordFormConfig, this.curRowData)
            }
        } as FormModalDto
    }

    // 重置PC密码
    resetPcPasswordFormConfig = this.initResetPcPasswordFormConfig() as FormModalDto
    initResetPcPasswordFormConfig() {
        return {
            title: '重置PC密码',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                password: {
                    name: '请输入新密码',
                    element: 'input',
                    type: 'password',
                    required: true,
                    params: {
                        suffix: () => (
                            <div
                                class="cursor-pointer"
                                onClick={() => this.toggleEye('resetPcPasswordFormConfig')}
                            >
                                {this.isEyeOpen ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                            </div>
                        )
                    }
                }
            },
            complete: async () => {
                const data = getModelValue(this.resetPcPasswordFormConfig)
                await confirm('重置密码后客户密码将被更改，请及时提醒客户更改密码。', '提示')
                await ressetPcPassword({
                    password: data.password,
                    saasUserId: this.curRowData.userId
                })
                message.success('更新成功')
                this.reloadPage()
                this.resetPcPasswordFormConfig.show = false
            },
            cancel: () => {
                this.resetPcPasswordFormConfig.show = false
            },
            init: () => {
                initModelValue(this.resetPcPasswordFormConfig, this.curRowData)
            }
        } as FormModalDto
    }

    onShowFormModal(row: VxeTableDataRow, formType: FormType) {
        this.curRowData = row
        this[formType].show = true
    }

    // 禁止/允许登录
    async onToggleLogin(row: VxeTableDataRow) {
        if (row.status === 0) {
            await confirm('禁止登录后，该账号将无法登录子弹发薪平台，确定禁止吗？', '提示')
            this.toggleLogin(1, row.userId)
        } else {
            this.toggleLogin(0, row.userId)
        }
    }

    async toggleLogin(status: number, userId: number) {
        await toggleLoginPcStatus({
            status,
            userId
        })
        message.success('操作成功')
        this.reloadPage()
    }

    toggleEye(formType: FormType) {
        this.isEyeOpen = !this.isEyeOpen
        this[formType].items.password.type = this.isEyeOpen ? 'text' : 'password'
    }

    // 设置/取消管理员
    async onToggleAdmin(row: VxeTableDataRow) {
        await setAdmin({
            companyId: row.companyId,
            isAdmin: row.isAdmin ? 0 : 1,
            userId: row.userId,
            type: 0
        })
        message.success('操作成功')
        this.reloadPage()
    }

    // 授权/取消授权席位管理员
    async onToggleSeatAdmin(row: VxeTableDataRow) {
        if (row.isSeatAdmin) {
            await confirm(
                '该成员为审批流中的成员，取消发薪席位后将从审批流中移除，请与客户确定好后再取消，如确定取消发薪席位，点击确定取消，取消席位后该操作不可撤回',
                '确定取消发薪席位？'
            )
        }
        await this.handleSeatAdmin(row)
    }
    async handleSeatAdmin(row: VxeTableDataRow) {
        await setSeatAdmin({
            companyId: row.companyId,
            isSeatAdmin: !row.isSeatAdmin,
            userId: row.userId
        })
        message.success('操作成功')
        this.reloadPage()
    }

    // 修改角色（用新接口，不再区分小程序还是pc）
    async onSetRole(row: VxeTableDataRow, role: RoleCnEnum) {
        console.log(row)
        await changeRole({
            id: row.id,
            isAdmin: role
        })
        message.success('操作成功')
        this.reloadPage()
    }

    async onSetSuperAdmin(row: VxeTableDataRow) {
        await setAdmin({
            companyId: row.companyId,
            isAdmin: 1,
            userId: row.userId,
            type: 1
        })
        message.success('操作成功')
        this.reloadPage()
    }

    async getSeatData() {
        const res = await getSeatInfo({
            companyId: this.companyId
        })
        this.seatData = res
    }

    onLoadData(page: number, size: number, filters: AnyObject) {
        if (!this.companyId) return []
        return getTeamMembersList({
            companyId: this.companyId,
            pageNum: page,
            pageSize: size,
            ...filters
        })
    }

    async onMounted() {
        super.onMounted()
        this.getSeatData()
    }

    renderToolbar() {
        return (
            <div class="px-20px">
                <div class="bg-yellow-100 border-1 border-solid border-yellow-100 rounded-md bg-opacity-10 text-base px-12px py-8px text-black-200 mb-12px">
                    <ExclamationCircleFilled style={{ color: '#FFA814' }} />
                    <span class="ml-9px">当前客户共有</span>
                    <span class="text-blue-default px-10px">{this.seatData.hasSeat}</span>
                    <span>个发薪席位，目前还可分配</span>
                    <span class="text-blue-default px-10px">
                        {(this.seatData?.hasSeat ?? 0) - (this.seatData?.useSeat ?? 0)}
                    </span>
                    <span>个发薪席位</span>
                </div>
            </div>
        )
    }

    render() {
        return (
            <>
                {super.render()}
                {/* 重置手机号 */}
                {renderModal(this.resetPhoneFormConfig)}
                {/* 修改角色 */}
                {renderModal(this.editRoleFormConfig)}
                {/* 重置小程序登录密码 */}
                {renderModal(this.resetMiniProgramPasswordFormConfig)}
                {/* 重置PC登录密码 */}
                {renderModal(this.resetPcPasswordFormConfig)}
            </>
        )
    }
}

export default toNative<{ companyId: number }, {}>(TeamManagement)
